package com.xuanzheng.company.servlet;

import com.google.gson.Gson;
import com.xuanzheng.company.dao.CompanyDao;
import com.xuanzheng.company.dao.impl.CompanyDaoImpl;
import com.xuanzheng.company.entity.Company;
import com.xuanzheng.company.entity.User;
import com.xuanzheng.company.service.UserService;
import com.xuanzheng.company.service.impl.UserServiceImpl;
import com.xuanzheng.company.util.DBUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

@WebServlet("/login")
public class LoginServlet extends HttpServlet {
    private UserService userService = new UserServiceImpl();
    private CompanyDao companyDao = new CompanyDaoImpl();
    private Gson gson = new Gson();

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 设置请求和响应的字符编码
        req.setCharacterEncoding("UTF-8");
        resp.setContentType("application/json;charset=UTF-8");
        
        PrintWriter out = resp.getWriter();
        Map<String, Object> result = new HashMap<>();
        
        try {
            // 获取请求参数
            String phone = req.getParameter("phone");
            String password = req.getParameter("password");
            String roleStr = req.getParameter("role");
            
            // System.out.println("登录请求 - 手机号: " + phone + ", 角色: " + roleStr);
            
            // 参数验证
            if (phone == null || phone.trim().isEmpty() || 
                password == null || password.trim().isEmpty() ||
                roleStr == null || roleStr.trim().isEmpty()) {
                
                // System.out.println("登录失败 - 参数不完整");
                result.put("success", false);
                result.put("message", "请填写完整的登录信息");
                out.write(gson.toJson(result));
                return;
            }
            
            // 测试数据库连接
            if (!DBUtil.testConnection()) {
                // System.out.println("登录失败 - 数据库连接测试失败");
                result.put("success", false);
                result.put("message", "系统维护中，请稍后再试");
                out.write(gson.toJson(result));
                return;
            }
            
            int role;
            try {
                role = Integer.parseInt(roleStr); // 0-普通用户，1-公司负责人
            } catch (NumberFormatException e) {
                // System.out.println("登录失败 - 角色参数格式错误: " + roleStr);
                result.put("success", false);
                result.put("message", "角色参数错误");
                out.write(gson.toJson(result));
                return;
            }
            
            // 先检查用户是否存在且未被禁用
            User checkUser = userService.findByPhone(phone);
            if (checkUser != null && checkUser.getStatus() == 0) {
                // System.out.println("登录失败 - 用户已被禁用: " + phone);
                result.put("success", false);
                result.put("message", "您的账号已被系统管理员禁用（个人禁用），无法登录系统。请联系系统管理员：14749901974，了解详情。");
                out.write(gson.toJson(result));
                return;
            }
            
            // 调用登录服务
            User user = userService.login(phone, password, role);
            
            if (user != null) {
                // System.out.println("登录成功 - 用户: " + user.getName() + " (" + user.getId() + ")");
                
                // 检查公司状态（如果用户属于某个公司）
                if (user.getCompanyId() != null && !user.getCompanyId().isEmpty()) {
                    Company company = companyDao.getCompanyById(user.getCompanyId());
                    if (company != null && company.getStatus() == 0) {
                        // 公司已被禁用
                        // System.out.println("登录失败 - 用户所在公司已被禁用: " + company.getName());
                        result.put("success", false);
                        result.put("message", "您所在的公司已被系统管理员禁用（公司禁用），无法登录系统。请联系系统管理员：14749901974，了解详情。");
                        out.write(gson.toJson(result));
                        return;
                    }
                }
                
                // 登录成功，将用户信息保存到session
                HttpSession session = req.getSession();
                session.setAttribute("user", user);
                
                result.put("success", true);
                result.put("message", "登录成功");
                result.put("user", user);
                
                // 根据角色重定向到不同页面
                if (role == 0) {
                    result.put("redirect", "normal_home.html");
                } else if (role == 1) {
                    result.put("redirect", "manager_home.html");
                }
            } else {
                // System.out.println("登录失败 - 手机号或密码错误: " + phone);
                result.put("success", false);
                result.put("message", "手机号或密码错误，或者角色选择错误");
            }
        } catch (Exception e) {
            System.err.println("登录过程发生异常: " + e.getMessage());
            e.printStackTrace();
            result.put("success", false);
            result.put("message", "系统错误，请稍后再试");
        }
        
        // 输出JSON响应
        out.write(gson.toJson(result));
        out.flush();
        out.close();
    }
} 